import uuid
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginUPForm
from utils.image_code import check_code
from io import BytesIO
from web import models
from django.db.models import Q
import datetime


def register(request):
    """注册"""
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    form = RegisterModelForm(request.POST)
    if form.is_valid():
        # 通过验证要写入数据库(密文加密)
        instance = form.save()
        # 创建交易记录表
        t_prince = models.CommodityPrices.objects.filter(category=1, title="个人免费版").first()
        models.Transaction.objects.create(
            t_status=2,
            t_order=str(uuid.uuid4()),
            t_user=instance,
            t_price=t_prince,
            t_pay=0,
            t_start=datetime.datetime.now(),
            t_number=0,
        )
        return JsonResponse({'status': True, 'url': '/websass/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """发送短信"""

    form = SendSmsForm(request, data=request.GET)

    if form.is_valid():
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "error": form.errors})


def login_sms(request):
    if request.method == 'GET':
        form = LoginSMSForm()
        """短信登陆"""
        return render(request, 'login_sms.html', {'form': form})
    form = LoginSMSForm(request.POST)
    if form.is_valid():
        # 用户输入正确，可以登陆
        user_object = form.cleaned_data['mobile_phone']
        # 保存到session中
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        request.session['user_name'] = user_object.username
        return JsonResponse({"status": True, 'url': '/wabsass/index/'})
    return JsonResponse({"status": False, 'error': form.errors})


def login(request):
    """用户名和密码登陆"""
    if request.method == 'GET':
        form = LoginUPForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginUPForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_object:
            # 登陆成功
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect("/websass/index")
        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def image_code(request):
    image_object, code = check_code()
    print(image_object)
    # 3. 写入内存(Python3)
    # 把code写入到session中
    request.session['image_code'] = code
    # 给验证码设置超时时间位60秒
    request.session.set_expiry(60)
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect("websass:index")
